import numpy as np
import cv2
from tqdm import tqdm
import multiprocessing
import os

OPERATION_DIR="./yjjy_tempt"

def get_center_value_1(array):



    return int(array.mean())


def get_relative_center(arr):
    FOLD = 32
    image_nums = 9
    sig = np.zeros(shape=(8, image_nums + 1), dtype="uint8")
    #print(sig.shape)
    #print(sig)
    #print(sig[7, 7])
    j = 0
    for i in arr:
        # print(i)
        # print((FOLD*0-1))
        # print((FOLD*1-1))
        # print(11>=(FOLD*0-1) and 11<=(FOLD*1-1))
        if i >= (0) and i <= (FOLD * 1 - 1):
            sig[0, j] = i
            sig[0, 9] += 1
        if i >= (FOLD * 1) and i <= (FOLD * 2 - 1):
            sig[1, j] = i
            sig[1, 9] += 1
        if i >= (FOLD * 2) and i <= (FOLD * 3 - 1):
            sig[2, j] = i
            sig[2, 9] += 1
        if i >= (FOLD * 3) and i <= (FOLD * 4 - 1):
            sig[3, j] = i
            sig[3, 9] += 1
        if i >= (FOLD * 4) and i <= (FOLD * 5 - 1):
            sig[4, j] = i
            sig[4, 9] += 1
        if i >= (FOLD * 5) and i <= (FOLD * 6 - 1):
            sig[5, j] = i
            sig[5, 9] += 1
        if i >= (FOLD * 6) and i <= (FOLD * 7 - 1):
            sig[6, j] = i
            sig[6, 9] += 1
        if i >= (FOLD * 7) and i <= (FOLD * 8 - 1):
            sig[7, j] = i
            sig[7, 9] += 1
        j += 1

    #print(sig)
    #
    dim = np.argmax(sig[:, 9])
    #print(dim)
    image_num = sig[dim, 9]
    image_sum = np.sum(sig[dim, 0:9])
    #print( (sig[dim, 0:9]))
    #print(image_sum)
    #print(">>>>>>>>>>")
    image_avg = int(image_sum / image_num)
    return image_avg



R_FOLD=int(1080/10)
SUB_IMAGE_DIC = {}
def sub_process(i):
    img1 = cv2.imread("1.png")
    img2 = cv2.imread("2.png")
    img3 = cv2.imread("3.png")
    img4 = cv2.imread("4.png")
    img5 = cv2.imread("5.png")
    img6 = cv2.imread("6.png")
    img7 = cv2.imread("7.png")
    img8 = cv2.imread("8.png")
    img9 = cv2.imread("9.png")
    # img4 = cv2.imread("4.png")
    # img5 = cv2.imread("5.png")
    # img_stack = np.stack((img4,img5),axis=3)
    img_stack = np.stack((img1, img2, img3, img4, img5, img6, img7, img8, img9), axis=3)
    [R, G, B, D] = img_stack.shape

    img_k_means_sub = np.zeros(shape=(R_FOLD,G,B), dtype="uint8")
    for i in tqdm(range(R_FOLD)):
    #print("processing>>>>>",i,G,B)
        for j in range(G):

            for k in range(B):
                #print(k)
                #print(get_relative_center(img_stack[i,j,k]))
                img_k_means_sub[i, j, k] = get_relative_center(img_stack[i,j,k])
                #if k==B-1:
                    #print("process>>>>>", i,"finished!")
    SUB_IMAGE_DIC[i]=img_k_means_sub

def test_process_pool(process_num, R,G,B,img_stack):
    pool = multiprocessing.Pool(processes=process_num)
    for i in range(R):
        pool.apply_async(sub_process, (i,G,B,img_stack))  # 维持执行的进程总数为processes，当一个进程执行完毕后会添加新的进程进去
    pool.close()  # join函数等待所有子进程结束
    pool.join()




def pixel_is_process(img_array):
    [R, G, B] = img_array.shape
    process_image_array = []
    for i in range(R):
        for j in range(G):
            #for i in range(R):
            #bool_list =  == [0, 0, 0]
            if not ( img_array[i, j, 0] == 0 and img_array[i, j, 1]==0 and img_array[i, j, 2]==0):
                process_image_array.append([i,j])
    return process_image_array
    # print(bool_list)
    # print(type(bool_list))


#输入九张图片的文件夹目录位置

def get_avg_img(operation_dir):
    img_num=os.listdir(operation_dir).__len__()
    all_file=os.listdir(operation_dir)
    files_path=[]
    #img_list=np.stack(())
    # print(all_file)
    for i in range(img_num):
        files_path.append(cv2.imread((os.path.join(operation_dir,all_file[i]))))


    img_list = np.stack((files_path[0],files_path[1],files_path[2],files_path[3],files_path[4],files_path[5],files_path[6],files_path[7],files_path[8]),axis=3)
    img_shape=  files_path[0].shape
    # print(img_shape)
    # for img_index in range(1,img_num):
    #     print(img_index)
    #     file_dir=os.path.join(operation_dir,all_file[img_index])
    #     img_list=np.stack((img_list,cv2.imread(file_dir)),axis=3)
        #img_num+=1
        #img_num=img_list.__len__()

    img_k_means = np.zeros(shape=img_shape, dtype="uint8")
    #print(">>>>>")
    #print(img_k_means.shape)
    #print(img_stack.shape)
    #[R, G, B, D] = img_stack.shape

    process_image_array=pixel_is_process(files_path[0])

    #print(process_image_array)
    for sub_list in tqdm(process_image_array):
        k=0
        #print("*******",sub_list)
        for k in range(3):
            # print(k)
            # print(">>>>>>")
            # print(sub_array)
            # print(img_stack[sub_list[0], sub_list[1],k])
            img_k_means[sub_list[0], sub_list[1], k] = get_relative_center(img_list[sub_list[0], sub_list[1],k])
            #print(temp)
            #= temp
            #img_k_means[sub_list[0], sub_list[1], k] =177
            k+=1
    print(img_k_means.shape)
    return img_k_means

def get_avg_img_(region_images,region_num,time):
    # img_num=os.listdir(operation_dir).__len__()
    for i in range(region_num):
        all_file=region_images[i]
        #print("all_file llen",all_file.__len__())
        files_path=[]
        #img_list=np.stack(())
        # print(all_file)
        for j in range(all_file.__len__()):
            files_path.append(cv2.imread((os.path.join(os.path.join(OPERATION_DIR,time),all_file[j]))))

        #print("filesalllen:" ,files_path.__len__())
        img_list = np.stack((files_path[0],files_path[1],files_path[2],files_path[3],files_path[4],files_path[5],files_path[6],files_path[7],files_path[8]),axis=3)
        img_shape=  files_path[0].shape

        img_k_means = np.zeros(shape=img_shape, dtype="uint8")
        #print(">>>>>")
        #print(img_k_means.shape)
        #print(img_stack.shape)
        #[R, G, B, D] = img_stack.shape

        process_image_array=pixel_is_process(files_path[0])

        #print(process_image_array)

        for sub_list in tqdm(process_image_array):
            k=0
            #print("*******",sub_list)
            for k in range(3):
                # print(k)
                # print(">>>>>>")
                # print(sub_array)
                # print(img_stack[sub_list[0], sub_list[1],k])
                img_k_means[sub_list[0], sub_list[1], k] = get_relative_center(img_list[sub_list[0], sub_list[1],k])
                #print(temp)
                #= temp
                #img_k_means[sub_list[0], sub_list[1], k] =177
                k+=1
        #print(os.path.join(OPERATION_DIR,str(i)+".png"))

        cv2.imwrite(os.path.join(os.path.join(OPERATION_DIR,time),str(i)+".jpg"),img_k_means)

        #print("get avg_img:", os.path.join(os.path.join(OPERATION_DIR, time), str(i) + ".jpg"), img_k_means)
    #print(img_k_means.shape)
    #return img_k_means

def extract_background(region_num,time):
    #region_num = 3
    region_images = []
    for i in range(region_num):
        #print(i)
        sub_region_images = []
        for file in os.listdir(os.path.join(OPERATION_DIR,time)):
            # print(file)

            if file[0] == str(i):
                #print(file)
                sub_region_images.append(file)
        region_images.append(sub_region_images)
    # print(region_images[1])
    get_avg_img_(region_images, region_num,time)
if __name__ == '__main__':
    region_num=2
    extract_background(region_num)
    # region_images=[]
    # for i in range(region_num):
    #     print(i)
    #     sub_region_images = []
    #     for file in os.listdir(OPERATION_DIR):
    #         #print(file)
    #
    #         if file[0]==str(i):
    #             print(file)
    #             sub_region_images.append(file)
    #     region_images.append(sub_region_images)
    # #print(region_images[1])
    # get_avg_img_(region_images,region_num)

    # print(">>>>>>>")
    # cv2.imshow('k-means img', img_k_means)
    # cv2.waitKey(0)
    # cv2.destroyWindow('k-means img')
    #img_k_means=get_avg_img("croped_image/")
    # img1 = cv2.imread("1.png")
    # img2 = cv2.imread("2.png")
    # img3 = cv2.imread("4.png")
    # img4 = cv2.imread("3.png")
    # img5 = cv2.imread("5.png")
    # img6 = cv2.imread("6.png")
    # img7 = cv2.imread("7.png")
    # img8 = cv2.imread("8.png")
    # img9 = cv2.imread("9.png")
    #
    #
    # print(pixel_is_process(img1))
    #
    #
    #
    # img_stack = np.stack((img1, img2, img3, img4, img5, img6, img7, img8, img9), axis=3)
    # img_k_means = np.zeros(shape=img1.shape, dtype="uint8")
    # print(img_k_means.shape)
    # print(img_stack.shape)
    # [R, G, B, D] = img_stack.shape
    # img_k_means = np.zeros(shape=img1.shape, dtype="uint8")

    # for i in tqdm(range(R)):
    #     for j in range(G):
    #         for k in range(B):
    #             img_k_means[i, j, k] = get_relative_center(img_stack[i,j,k])


    # process_image_array=pixel_is_process(img1)
    #
    # print(process_image_array)
    # for sub_list in tqdm(process_image_array):
    #     k=0
    #     #print("*******",sub_list)
    #     for k in range(3):
    #         # print(k)
    #         # print(">>>>>>")
    #         # print(sub_array)
    #         # print(img_stack[sub_list[0], sub_list[1],k])
    #         img_k_means[sub_list[0], sub_list[1], k] = get_relative_center(img_stack[sub_list[0], sub_list[1],k])
    #         #print(temp)
    #         #= temp
    #         #img_k_means[sub_list[0], sub_list[1], k] =177
    #         k+=1
    #
    #


    # img_k_means[sub_list[0], sub_list[1], k] = get_relative_center(img_stack[sub_list[0], sub_list[1],k])
    #print(pixel_is_process(img1))
    #print(img1)
    # zeros=np.zeros(shape=(2,3,3),dtype="uint8")
    # bool_list=zeros[1,2,:]==[0,0,0]
    # print(bool_list)
    # print(type(bool_list))
    # print(bool_list[1] and bool_list[2] and bool_list[0])
    # img_k_means=np.zeros(shape=img1.shape,dtype="uint8")
    # print(img_k_means.shape)
    # print(img_stack.shape)
    # [R, G, B, D] = img_stack.shape
    # print(R, G, B)
    #sub_process(i=100,G=G,B=B,img_stack=img_stack)

    #process_list=np.arange(R).tolist()
    #test_process_pool(process_num=32, task_num=R)
    #print(process_list)
    # threads = []
    # t1 = Thread(target=sub_process, args=(1,))
    # threads.append(t1)
    # t2 = Thread(target=sub_process, args=(0,))
    # threads.append(t2)
    # for t in threads:
    #     t.setDaemon(True)
    #     t.start()
    #     t.join()
    # thread_list=[]
    # for i in tqdm(range(R)):
    #     t1 = Thread(target=sub_process,args=(i))
    #     t1.start()
    #     t1.join()
    #

    #    thread_list.append(threading.Thread(target=sub_process, args=(i,)))
    # reqs = threadpool.makeRequests(sub_process, process_list)
    # pool=threadpool.ThreadPool(2000)
    # for item in reqs:
    #     pool.putRequest(item)
    #     # 阻塞等待
    # pool.wait()
    # # sub_process(100)
    # [pool.putRequest(r) for r in reqs]
    # pool.join()
    #print(thread_list.__len__())
    #     for j in range(G):
    #         for k in range(B):
    #
    #             #print(1)
    #             img_k_means[i, j, k] = get_relative_center(img_stack[i,j,k])


    #test_process_pool(16,R,G,B,img_stack)


    #print(img_k_means)

    # print(SUB_IMAGE_DIC[1].shape)
    # img_k_means=np.row_stack(SUB_IMAGE_DIC[0],SUB_IMAGE_DIC[1])
    # # print(">>>>>>>")
    # cv2.imshow('k-means img', img_k_means)
    # cv2.waitKey(0)
    # cv2.destroyWindow('k-means img')

    #print(type(img))
    # print(img4)
    # print(img5)
    # print(img4.shape)
    #print(img_stack)
    #print(img_stack.shape)
    #print(np.shape(img_stack))
    #print(np.shape(img1))
    #print(img_stack)